<template>
  <a-modal :title="title" :width="1250" :visible="visible" @ok="handleOk" @cancel="handleCancel"
    :cancelText="$t('systemManagement.close')" wrapClassName="ant-modal-cust-warp"
    style="top:5%;height: 100%;overflow-y: hidden">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper" v-if="selectType === 'list'" v-show="false">
      <!-- 搜索区域 -->
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :md="6" :sm="24">
            <a-form-item :label="$t('setailManagement.documentNo')" :labelCol="{ span: 5 }"
              :wrapperCol="{ span: 18, offset: 1 }">
              <a-input :placeholder="$t('inPrint.pleaseDocumentNumber')" v-model="queryParam.number"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item :label="$t('setailManagement.productInformation')" :labelCol="{ span: 5 }"
              :wrapperCol="{ span: 18, offset: 1 }">
              <a-input :placeholder="$t('reportQuery.barcodeModel')" v-model="queryParam.materialParam"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item :label="$t('setailManagement.documentDate')" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-range-picker style="width: 100%" v-model="queryParam.createTimeRange" format="YYYY-MM-DD"
                :placeholder="[$t('setailManagement.startTime'), $t('setailManagement.endTime')]" @change="onDateChange"
                @ok="onDateOk" />
            </a-form-item>
          </a-col>
          <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
            <a-col :md="6" :sm="24">
              <a-button type="primary" @click="searchQuery">{{ $t('setailManagement.query') }}</a-button>
              <a-button style="margin-left: 8px" @click="searchReset">{{ $t('setailManagement.reset') }}</a-button>
            </a-col>
          </span>
        </a-row>
      </a-form>
    </div>
    <!-- table区域-begin -->
    <a-table v-if="selectType === 'list'" bordered ref="table" rowKey="id" :columns="columns"
      :dataSource="dataSource" :pagination="ipagination" :loading="loading"
      :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange, type: getType }"
      :customRow="rowAction" @change="handleTableChange">
      <span slot="numberCustomRender" slot-scope="text, record">
        <a @click="myHandleDetail(record)">{{ record.number }}</a>
      </span>
      <!-- <template slot="customRenderStatus" slot-scope="text, record">
        <template v-if="!queryParam.purchaseStatus">
          <a-tag v-if="record.status === '0'" color="red">{{ $t('setailManagement.notApproved') }}</a-tag>
          <a-tag v-if="record.status === '1'" color="green">{{ $t('setailManagement.reviewed') }}</a-tag>
          <a-tag v-if="record.status === '2' && queryParam.subType === '采购订单'" color="cyan">{{
              $t('manuManagement.completePurchase')
          }}</a-tag>
          <a-tag v-if="record.status === '2' && queryParam.subType === '销售订单'" color="cyan">{{
              $t('manuManagement.completeSales')
          }}</a-tag>
          <a-tag v-if="record.status === '3' && queryParam.subType === '采购订单'" color="blue">{{
              $t('manuManagement.partialProcurement')
          }}</a-tag>
          <a-tag v-if="record.status === '3' && queryParam.subType === '销售订单'" color="blue">{{
              $t('manuManagement.partialSales')
          }}</a-tag>
        </template>
        <template v-if="queryParam.purchaseStatus">
          <a-tag v-if="record.purchaseStatus === '0'" color="red">{{ $t('manuManagement.notPurchased') }}</a-tag>
          <a-tag v-if="record.purchaseStatus === '2' && queryParam.subType === '销售订单'" color="cyan">{{
              $t('manuManagement.completePurchase')
          }}</a-tag>
          <a-tag v-if="record.purchaseStatus === '3' && queryParam.subType === '销售订单'" color="blue">{{
              $t('manuManagement.partialProcurement')
          }}</a-tag>
        </template>
      </template> -->
    </a-table>
    <a-table v-if="selectType === 'detail'" bordered ref="table" size="middle" rowKey="id" :columns="columnsDetail"
      :dataSource="dataSourceDetail" :loading="loading"
      :rowSelection="{ selectedRowKeys: selectedDetailRowKeys, onChange: onSelectDetailChange, type: 'checkbox' }"
      @change="handleTableChange">
    </a-table>
    <!-- table区域-end -->
    <!-- 表单区域 -->
    <bill-detail ref="billDetail"></bill-detail>
  </a-modal>
</template>

<script>
import BillDetail from '../../bill/dialog/BillDetail'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { findBillDetailByNumber, getDetailByTransportNo } from '@/api/api'
import { getAction } from '@/api/manage'
import { FormTypes } from '@/utils/JEditableTableUtil'
import Vue from 'vue'
export default {
  name: 'LinkFreightPaymentList',
  mixins: [JeecgListMixin],
  components: {
    BillDetail
  },
  data() {
    return {
      title: this.$t('setailManagement.operation'),
      visible: false,
      disableMixinCreated: true,
      selectedRowKeys: [],
      selectedDetailRowKeys: [],
      selectBillRows: [],
      selectBillDetailRows: [],
      showType: 'basic',
      selectType: 'list',
      linkNumber: '',
      deliveryMethod: '',
      arrivalTimeStr: '',
      organId: '',
      depotId: '',
      discount: '',
      deposit: '',
      remark: '',
      checkDepotId:'',
      queryParam: {
        number: "",
        organId: '',
        materialParam: "",
        type: "",
        subType: "",
        status: "",
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      // 表头
      columns: [
        { title: this.$t('setailManagement.documentDate'),dataIndex: 'billTimeStr', key: 'billTimeStr', width: '15%', type: FormTypes.input, readonly: true },
        { title: this.$t('purchasingManagement.TransportCompany'),dataIndex: 'transpotName', key: 'transpotName', width: '20%', type: FormTypes.inputNumber, statistics: true, readonly: true },
        { title: this.$t('purchasingManagement.trackingNumber'),dataIndex: 'billNo', key: 'billNo', width: '20%', type: FormTypes.inputNumber, statistics: true, readonly: true },
        {
          title: this.$t('manuManagement.purchaseOrder'),dataIndex: 'number', key: 'number', width: '20%', type: FormTypes.inputNumber, statistics: true, placeholder: this.$t('inPrint.pleaseTnter') + '${title}'
        },
        {
          title: this.$t('purchasingManagement.totalAmount'),dataIndex: 'eachAmount',  key: 'eachAmount', width: '10%', type: FormTypes.inputNumber, statistics: true, placeholder: this.$t('inPrint.pleaseTnter') + '${title}',
          validateRules: [{ required: true, message: '${title}' + this.$t('inPrint.cannotTe') }]
        },
      ],
      columnsDetail: [
        { title: this.$t('reportQuery.barcode'), dataIndex: 'barCode', width: 120 },
        { title: this.$t('reportQuery.name'), dataIndex: 'name', width: 100, ellipsis: true },
        { title: this.$t('reportQuery.specification'), dataIndex: 'standard', width: 100, ellipsis: true },
        { title: this.$t('reportQuery.model'), dataIndex: 'model', width: 150, ellipsis: true },
        { title: this.$t('reportQuery.unit'), dataIndex: 'unit', width: 50 },
        { title: this.$t('reportQuery.quantity'), dataIndex: 'operNumber', width: 80 },
        { title: this.$t('reportQuery.unitPrice'), dataIndex: 'unitPrice', width: 80 },
        { title: this.$t('reportQuery.amount'), dataIndex: 'allPrice', width: 80 },
        { title: this.$t('basicInformation.taxRate'), dataIndex: 'taxRate', width: 80 },
        { title: this.$t('inPrint.taxAmount'), dataIndex: 'taxMoney', width: 80 },
        { title: this.$t('inPrint.totalTax'), dataIndex: 'taxLastMoney', width: 80 },
        { title: this.$t('reportQuery.remarks'), dataIndex: 'remark', width: 100, ellipsis: true },
      ],
      dataSource: [],
      dataSourceDetail: [],
      url: {
        list: "/depotHead/list"
      }
    }
  },
  computed: {
    getType: function () {
      return 'radio';
    }
  },
  created() {
  },
  methods: {
    show(type, subType, organType, status, organId) {
      this.selectType = 'list'
      this.showType = 'basic'
      this.queryParam.type = type
      this.queryParam.subType = subType
      // this.queryParam.subType = dream
      this.queryParam.roleType = Vue.ls.get('roleType')
      this.queryParam.status = status
      this.queryParam.organId = organId
      this.columns[0].title = organType
      this.model = Object.assign({}, {});
      this.visible = true;
      this.loadData(1)
    },
    purchaseShow(type, subType, organType, status, purchaseStatus, organId) {
      this.selectType = 'list'
      this.showType = 'purchase'
      this.queryParam.type = type
      this.queryParam.subType = subType
      // this.queryParam.subType = '采购'
      this.queryParam.roleType = '全部数据'
      this.queryParam.status = status
      this.queryParam.organId = organId
      this.queryParam.purchaseStatus = purchaseStatus
      this.columns[0].title = organType
      this.model = Object.assign({}, {});
      this.visible = true;
      this.loadData(1)
    },
    myHandleDetail(record) {
      findBillDetailByNumber({ number: record.number }).then((res) => {
        if (res && res.code === 200) {
          let type = res.data.depotHeadType
          type = type.replace('其它', '')
          this.$refs.billDetail.show(res.data, type)
          this.$refs.billDetail.title = type + "-" + '详情'
        }
      })
    },
    open (transportId, type) {
      this.visible = true
      this.loading = true
      getDetailByTransportNo({custom3: transportId, type}).then(res => {
        this.dataSource = res.data
        this.loading = false
      })
    },
    close() {
      this.$emit('close');
      this.visible = false;
    },
    handleCancel() {
      this.close()
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },
    onSelectDetailChange(selectedRowKeys) {
      this.selectedDetailRowKeys = selectedRowKeys;
    },
    handleOk() {
      const data = this.dataSource[this.selectedRowKeys]
      if (data) {
        this.$emit('ok', data)
      }
      
      this.close()
      // if (this.selectType === 'list') {
      //   this.getSelectBillRows();console.log(this.selectBillRows)
      //   // this.selectType = 'detail'
      //   this.title = this.$t('popup.selectDocumentDetails')
      //   if (this.selectBillRows && this.selectBillRows.length > 0) {
      //     let record = this.selectBillRows[0]
      //     // console.log('sss',record)
      //     this.linkNumber = record.number
      //     this.deliveryMethod = record.deliveryMethod
      //     this.organId = record.organId
      //     this.depotId = record.depotId
      //     this.arrivalTimeStr = record.arrivalTimeStr
      //     this.discount = 0
      //     this.deposit = record.changeAmount - record.finishDeposit
      //     this.remark = record.remark
      //     this.checkDepotId = record.checkDepotId
      //     this.loadDetailData(1)
      //   }
      // } else {
      //   this.getSelectBillDetailRows();
      //   // console.log("discount",this.discount)
      //   let arrId = []
      //   this.selectBillDetailRows.forEach(item => {
      //     arrId.push(item.materialId)
      //   });

      //   arrId = arrId.toString()
      //   localStorage.setItem('materialIds', arrId)
      //   this.$emit('ok', this.selectBillDetailRows, this.linkNumber, this.organId, this.discount, this.deposit, this.remark, this.arrivalTimeStr, this.depotId, this.deliveryMethod)
      //   this.close();
      // }
    },
    //查询明细列表 
    loadDetailData(arg) {
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1;
      }
      if (this.selectBillRows && this.selectBillRows.length > 0) {
        let record = this.selectBillRows[0]
        let param = {
          headerId: record.id,
          mpList: '',
          linkType: this.showType
        }
        this.loading = true;
        getAction('/depotItem/getDetailList', param).then((res) => {
          if (res.code === 200) {
            let list = res.data.rows;
            let listEx = []
            for (let j = 0; j < list.length; j++) {
              let info = list[j];
              info.meId = list[j].materialExtendId
              console.log("error");
              //去掉已经全部转换的明细
              if (info.preNumber !== info.finishNumber) {
                listEx.push(info)
              }
            }
            this.dataSourceDetail = listEx
            this.ipagination.total = res.data.total;
            this.dataSourceDetail.forEach(item => {
              this.selectedDetailRowKeys.push(item.id)
            });
          }
          if (res.code === 510) {
            this.$message.warning(res.data)
          }
          this.loading = false;
        })
      }
    },
    onDateChange: function (value, dateString) {
      this.queryParam.beginTime = dateString[0];
      this.queryParam.endTime = dateString[1];
    },
    onDateOk(value) {
      console.log(value);
    },
    searchReset() {
      this.queryParam = {
        type: this.queryParam.type,
        subType: this.queryParam.subType,
        status: "1,3"
      }
      this.loadData(1);
    },
    getSelectBillRows() {
      let dataSource = this.dataSource;
      this.selectBillRows = [];
      for (let i = 0, len = dataSource.length; i < len; i++) {
        if (this.selectedRowKeys.includes(dataSource[i].id)) {
          this.selectBillRows.push(dataSource[i]);
        }
      }
    },
    getSelectBillDetailRows() {
      let dataSource = this.dataSourceDetail;
      this.selectBillDetailRows = [];
      for (let i = 0, len = dataSource.length; i < len; i++) {
        if (this.selectedDetailRowKeys.includes(dataSource[i].id)) {
          this.selectBillDetailRows.push(dataSource[i]);
        }
      }
    },
    rowAction(record, index) {
      return {
        on: {
          click: () => {
            let arr = []
            arr.push(record.id)
            this.selectedRowKeys = arr
          },
          dblclick: () => {
            // console.log(record,index)
            // let arr = []
            // arr.push(record.id)
            this.selectedRowKeys = [index]
            this.handleOk()
          }
        }
      }
    }
  }
}
</script>

<style scoped>

</style>